#include "jpmaster.h"

JpMaster::JpMaster(MastSlaveMap data)
{

    _info=data;
    foreach (QString ip, data.slaveip) {
        ClientList cl;
        cl.ip=ip;
        cl.alive=0;
        cl.port=0;
        cl.socket=NULL;
        _clientlist.append(cl);
    }
    _ip=data.masterip;
    st=new STsend(this);

}

JpMaster::~JpMaster()
{
   st->stop();
   st->wait();


}

void JpMaster::run(){
    serverInit();

    QMap<long,QString>m;
    m[0]="sssssssss";
    m[1]="xxxxxxxxx";
    m[2]="ddddddddd";
    m[3]="bbbbbbbbbb";
    qRegisterMetaType<InMapData>("InMapData");
    connect(st,SIGNAL(WriteSignals(const InMapData,QTcpSocket*)),this,SLOT(JPWrite(const InMapData,QTcpSocket*)));
    st->init(&_clientlist,m);
    st->start();




}
//客户端连接时执行的逻辑
void JpMaster::serverConnectionLogic(QTcpSocket *sk){
     saveClient(sk);
    // showClientInfo(_clientlist);
     if(sk->isOpen()){
        //sk->write("欢迎登录系统!");
     }

}

//客户端断开连接执行逻辑
void JpMaster::serverDisConnectionLogic(QTcpSocket *sk){
    QString cip=sk->peerAddress().toString();
    for(int k=0;k<_clientlist.length();k++){
        if(_clientlist[k].ip==cip&&_clientlist[k].alive==1){
            _clientlist[k].port=0;
            _clientlist[k].alive=0;
            _clientlist[k].socket->close();
            _clientlist[k].socket=NULL;
        }
    }
}


//客户端发来消息
void JpMaster::readServerLogic(QTcpSocket* socket){
    ClientList c=getClient(&_clientlist,socket);
    //qDebug()<<c.socket<<"客户端发来消息"<<socket;
}

//当客户端连接时候,检查是否存在客户端ip,存在则保持socket并激活
void JpMaster::saveClient(QTcpSocket *sk){
    QString cip=sk->peerAddress().toString();
    for(int k=0;k<_clientlist.length();k++){
        if(_clientlist[k].ip==cip&&_clientlist[k].alive==0){
            QVector<ClientList> tmp=getActiveClient(&_clientlist);
            _clientlist[k].id=tmp.length()+1;
            _clientlist[k].port=sk->peerPort();
            _clientlist[k].alive=1;

            _clientlist[k].socket=sk;

        }else if(_clientlist[k].ip==cip&&_clientlist[k].alive==1){
            sk->write("已经存在连接了!连接断开.");
            sk->close();
        }
    }
}


//服务端发送数据
void JpMaster::JPWrite(const InMapData inmap, QTcpSocket *sk){
    //qDebug()<<data;
    int len=sizeof(inmap.key)+inmap.value.length();
    QByteArray i;
    i.resize(len);

    memcpy(i.data(),&inmap,len);
    InMapData *t2=(InMapData *)i.data();

    //qDebug()<<t2->key<<t2->value;

    qDebug()<<sk->write(i,len);
    //sk->waitForBytesWritten(-1);
    sk->flush();
    i.clear();
}
